<template>
  <div>
    <el-upload class="image-uploader" :action="url" :show-file-list="false" :on-preview="viewImg" :on-remove="removeImg" :on-success='successImg' :on-error="errorImg" :on-exceed="exceedImg" :before-upload="beforeImageUpload">
      <img v-if="imgUrl" :src="imgUrl" class="image">
      <i v-else class="el-icon-plus image-uploader-icon"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl">
    </el-dialog>
  </div>
</template>
<script>
import utils from '../ttJs/utils.js'
export default {
  name: 'uploadImage',
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      imgUrl: ''
    };
  },
  props: {
    value: [String],
    limit: {
      type: Number,
      default: 1
    },
    url: [String],
    index: {
      type: Number,
      default: 0
    }
  },
  mounted() {
    this.imgUrl = this.value;
  },
  computed: {},
  watch: {
    value: function(val) {
      this.imgUrl = val;
    }
  },
  methods: {
    removeImg(file, fileList) {
      this.imgUrl = "";
      this.$emit('getImg', this.imgUrl, this.index)
    },
    successImg(response, file, fileList) {
      this.imgUrl = response.info;
      this.$emit('getImg', this.imgUrl, this.index)
    },
    errorImg(err, file, fileList) {
      utils.fail('上传图片失败')
    },
    exceedImg(files, fileList) {
      utils.fail('只能上传' + fileList.length + '张图片')
    },
    viewImg(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    beforeImageUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    }
  }
};

</script>
<style rel="stylesheet/scss" lang="scss">
input[type="file"] {
  display: none !important;
}
.image-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.image-uploader .el-upload:hover {
  border-color: #409EFF;
}
.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.image {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
